//
//  CALayer+TimesAnimation.m
//  WCGradientLayerExample
//
//  Created by 陈晓强 on 2016/12/21.
//  Copyright © 2016年 huangwenchen. All rights reserved.
//

#import "CALayer+TimesAnimation.h"

@implementation CALayer (TimesAnimation) 
@dynamic animateValue;
@dynamic currentValue;

- (void)animateToValue:(id)value atTime:(NSTimeInterval)beginTime {
    CABasicAnimation *anim = [self animationAtTime:beginTime toValue:value];
    self.animateValue = value;
    [[self animateLayer] addAnimation:anim forKey:@(beginTime).stringValue];
}

- (void)animateWithValuesArray:(NSArray<NSNumber *> *)values atTimes:(NSArray<NSNumber *> *)times {
    int i = 0;
    self.animateValue = self.currentValue;
    for (id value in values) {
        NSTimeInterval beginTime = times[i].integerValue;
        CABasicAnimation *anim = [self animationAtTime:beginTime toValue:value];
        self.animateValue = value;
        [[self animateLayer] addAnimation:anim forKey: @(i).stringValue];
        i++;
    }
}

- (CABasicAnimation *)animationAtTime:(NSTimeInterval)time toValue:(id)value {
    CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:[self animateKeypath]];
    anim.duration = [self per_duration];
    anim.fillMode = kCAFillModeForwards;  
    anim.removedOnCompletion = NO;  
    //    anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    anim.delegate = self;  
    anim.fromValue = self.animateValue;
    anim.beginTime = CACurrentMediaTime() + time;
    anim.toValue = value;
    self.currentValue = value;
    return anim;
}

- (NSString *)animateKeypath {
    return @"";
}

- (CGFloat)per_duration {
    return 0.6;
}

- (CALayer *)animateLayer {
    return self;
}

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
    NSLog(@"stop");
//    [[self animateLayer] removeAnimationForKey:@""];
}
@end
